package com.calmcar.adas.service;

import android.graphics.Bitmap;
import android.graphics.ImageFormat;
import android.util.Log;

import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

/**
 * Created by lelexiao on 2018/5/5.
 */

public class MatProcess {

    public static Mat processData (byte[] frame, int height, int width, int mPreviewFormat ) {
        Mat mYuvFrameData= new Mat( height+ ( height/2), width, CvType.CV_8UC1);
        mYuvFrameData .put(0, 0, frame);
        Mat mRgba = new Mat();
        if (mPreviewFormat == ImageFormat.NV21)
            Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4);
        else if (mPreviewFormat == ImageFormat.YV12)
            Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGB_I420, 4); // COLOR_YUV2RGBA_YV12 produces inverted colors
        else if (mPreviewFormat == ImageFormat.YUV_420_888) {
//            assert (mUVFrameData != null);
//            Imgproc.cvtColorTwoPlane(mYuvFrameData, mUVFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21);
        } else
            throw new IllegalArgumentException("Preview Format can be NV21 or YV12");
        return mRgba;

    }

    public static Mat processData (byte[] frame, int width, int height){
        try{
            Mat mYuvFrameData= new Mat( height+ ( height/2), width, CvType.CV_8UC1);
            mYuvFrameData .put(0, 0, frame);
            Mat mRgba= new Mat();
            Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4);
            return mRgba;
        }catch (Exception e){
            e.printStackTrace();
        }
 return null;
    }

    public static Mat processDataRgbaToBgr (Mat rgbaMat){
        Mat rgbMat = new Mat();
        if(rgbaMat!=null ){
            Imgproc.cvtColor(rgbaMat, rgbMat, Imgproc.COLOR_RGBA2BGR);
        }else{
            return null;
        }
        return rgbMat;
    }

    public static byte[] processRgbDataToByteData(Mat rgbMat){
        byte[] buff_tmp = new byte[(int) (rgbMat.total() * rgbMat.channels())];
        rgbMat.get(0, 0, buff_tmp);
        return buff_tmp;
    }


   public static boolean convertMatToBitMap(Mat rgbaMat, Bitmap   mCacheBitmap  ){
       try {
           Utils.matToBitmap(rgbaMat, mCacheBitmap);
       } catch(Exception e) {

           Log.e("matprocess", "Mat type: " +rgbaMat);
           Log.e("matprocess", "Bitmap type: " + mCacheBitmap.getWidth() + "*" + mCacheBitmap.getHeight());
           Log.e("matprocess", "Utils.matToBitmap() throws an exception: " + e.getMessage());
           return false;
       }
       return true;
   }
}
